package com.ydgk.servlet;

import com.ydgk.bean.Admin;
import com.ydgk.dao.AdminDao;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

@WebServlet(name = "LoginServlet", urlPatterns = "/LoginServlet.action")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String CheckCode = request.getParameter("CheckCode");
        String remember = request.getParameter("remember");
        HttpSession session = request.getSession();
        String checkCode_session = (String) session.getAttribute("checkCode_session");
        session.removeAttribute("checkCode_session");
        Admin admin = new Admin();
        AdminDao adminDao = new AdminDao();
        try {
            BeanUtils.populate(admin,request.getParameterMap());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        if(checkCode_session!= null && checkCode_session.equalsIgnoreCase(CheckCode)){
            Admin newAdmin = adminDao.login(admin);
            if(newAdmin!=null){
                session.setAttribute("admin",newAdmin);
                if(remember!=null){
                    Cookie cookieName = new Cookie("aname",admin.getAname());
                    Cookie cookiePass = new Cookie("apass",admin.getApass());
                    cookieName.setMaxAge(60 * 60 * 24 * 15);
                    cookiePass.setMaxAge(60 * 60 * 24 * 15);
                    response.addCookie(cookieName);
                    response.addCookie(cookiePass);
                }
                response.sendRedirect(request.getContextPath()+"/home.jsp");
            }else{
                request.setAttribute("message","用户名或密码错误");
                request.getRequestDispatcher("login.jsp").forward(request,response);
            }
        }else{
            request.setAttribute("message","验证码错误");
            request.getRequestDispatcher("login.jsp").forward(request,response);
        }
    }


}
